<?php

namespace app\admin\controller;

//use app\admin\controller\agent\Agentstaff;
use app\admin\model\Admin;
use app\common\controller\Backend;
use Cassandra\Uuid;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Model;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class RobotUser extends Backend
{

    /**
     * RobotUser模型对象
     * @var \app\admin\model\RobotUser
     */
    protected $model = null;

    //protected $agentstaff = null;

    protected $admin = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\RobotUser;

        //$this->agentstaff = new \app\admin\model\agent\Agentstaff;

        $this->admin = new Admin();
    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            $admin = $this->admin->where([
                'status' => 'normal'
            ])->select();

            $list = [];
            foreach ($admin as $item => $value) {
                $list[$value->username] = $value->username;
            }

            $this->assignconfig("adminUserList", $list);
            $this->assign("loginUserId", $this->auth->username);
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
//            ->where([
//                'robotType' => 2
//            ])
//            ->join("admin", "admin.username = robotuser_list.agentID", "left")
            ->order($sort, $order)
//            ->field("robotuser_list.*, admin.nickname")
            ->paginate($limit);

        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
//            $agentstaffList = $this->agentstaff->where([
//                'status' => 1
//            ])->select();
            $admin = $this->admin->where([
                'status' => 'normal'
            ])->select();

            $list = [];
            foreach ($admin as $item => $value) {
                $list[$value->id] = $value->username;
            }

            $robotType = [
                1 => '爬虫机器人',
                2 => '经纪机器人'
            ];

            $this->assign("loginUserId", $this->auth->id);
            $this->assign("agentstaffList", $list);
            $this->assign("robotType", $robotType);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            $param = "'" . $params['agentID'] . "'," . $params['robotType'] . ",'" . $params['robotUser'] . "',
            '". $params['robotUser'] . "','" . $params['region'] . "',null,0,0,0,0,@_res";
            Db::query("call robotuser_add($param)");
            $result = true;
            Db::commit();

            //$this->error($param);
            
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    public function frequency($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->assign("robotUser", $ids);

            $data = Db::query("SELECT followInterval,
                     followMaxTask,
                     videoInterval,
                     videoMaxTask,
                     videoMaxLikes,
                     videoMaxSpeak,
                     verifyInterval,
                     verifyMaxTask 
            FROM agentrobot_set 
            WHERE robotUser = '" . $ids . "'");

            if (!empty($data)) {
                $this->assign('data', $data[0]);
            } else {
                $this->assign('data', [
                    'followInterval' => null,
                    'followMaxTask' => null,
                    'videoInterval' => null,
                    'videoMaxTask' => null,
                    'videoMaxLikes' => null,
                    'videoMaxSpeak' => null,
                ]);
            }
            return $this->view->fetch();
        }

        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
//        print_r($params);die;
        $result = false;
        Db::startTrans();
        try {
            $sql = "call agentrobot_param_set('" . $params['robotUser'] . "', " . $params['followInterval'] . ", " . $params['followMaxTask'] . ", "
                . $params['videoInterval'] . ", " . $params['videoMaxTask'] . ", " . $params['videoMaxLikes'] . ", "
                . $params['videoMaxSpeak'] . ", 60, 120, @_res)";

            Db::query($sql);
            $result = true;
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    public function robot()
    {
        if (false === $this->request->isPost()) {
            $girlOne = Db::table("dict_speak_script")->where(['speakType' => 1])->select();
            $girlTwo = Db::table("dict_speak_script")->where(['speakType' => 2])->select();
            $boyOne = Db::table("dict_speak_script")->where(['speakType' => 3])->select();
            $boyTwo = Db::table("dict_speak_script")->where(['speakType' => 4])->select();

            $girlOneData = [];
            $girlTwoData = [];
            $boyOneData = [];
            $boyTwoData = [];
            if (!empty($girlOne)) {
                foreach ($girlOne as $key => $value) {
                    $string = $value['speakDefault'];
                    if ($key < count($girlOne) - 1) {
                        $string .= "\n";
                    }
                    $girlOneData[] = $string;

                }
            }

            if (!empty($girlTwo)) {
                foreach ($girlTwo as $key => $value) {
                    $string = $value['speakDefault'];
                    if ($key < count($girlTwo) - 1) {
                        $string .= "\n";
                    }
                    $girlTwoData[] = $string;

                }
            }

            if (!empty($boyOne)) {
                foreach ($boyOne as $key => $value) {
                    $string = $value['speakDefault'];
                    if ($key < count($boyOne) - 1) {
                        $string .= "\n";
                    }
                    $boyOneData[] = $string;

                }
            }

            if (!empty($boyTwo)) {
                foreach ($boyTwo as $key => $value) {
                    $string = $value['speakDefault'];
                    if ($key < count($boyTwo) - 1) {
                        $string .= "\n";
                    }
                    $boyTwoData[] = $string;

                }
            }
//print_r($girlOneData);die;
            $this->assign("girlOne", $girlOneData);
            $this->assign("girlTwo", $girlTwoData);
            $this->assign("boyOne", $boyOneData);
            $this->assign("boyTwo", $boyTwoData);
            return $this->view->fetch();
        }

        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $result = false;
        Db::startTrans();
        try {

            $this->insertData("1", explode("\r\n", $params['girlOne']));
            $this->insertData("2", explode("\r\n", $params['girlTwo']));
            $this->insertData("3", explode("\r\n", $params['boyOne']));
            $this->insertData("4", explode("\r\n", $params['boyTwo']));

            $result = true;
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    private function insertData($type, $data)
    {
        Db::table("dict_speak_script")->where([
            'speakType' => $type
        ])->delete();
        foreach ($data as $item) {
            Db::query("call speak_script_set($type, null,'".$item."', '".$item."', 1, @_res)");
        }
    }

    public function stop($ids)
    {
        $result = false;
        Db::startTrans();
        try {
            Db::query("call robotuser_delete('$ids', @_res)");
            $result = true;
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error("操作失败");
        }
        $this->success();
    }
}
